//
//  EMMNewLoginViewController.m
//  EMMApp
//
//  Created by Mac on 16/8/2.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "EMMNewLoginViewController.h"
#import "LoginNewCell.h"
#import "LoginApi.h"
@interface EMMNewLoginViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (nonatomic, strong) UITableView *homeTableView;
@property (nonatomic, strong) UITextField *loginText;
@property (nonatomic, strong) UITextField *passordText;

@end

@implementation EMMNewLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _homeTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, EMM_HEIGHT) style:UITableViewStylePlain];
    _homeTableView.delegate = self;
    _homeTableView.dataSource = self;
    _homeTableView.backgroundColor = [UIColor colorFromHexCode:@"#f7f7f7"];
    _homeTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    if (@available(iOS 11.0, *)){
        _homeTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        _homeTableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);//导航栏如果使用系统原生半透明的，top设置为64
        _homeTableView.scrollIndicatorInsets = _homeTableView.contentInset;
    }
    [self.view addSubview:_homeTableView];
    _loginText.delegate = self;
    _passordText.delegate = self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableView 代理

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (EMM_HEIGHT == 480) {
        return 568;
    }
    return EMM_HEIGHT;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellId = @"LoginNewCellId";
    LoginNewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"LoginNewCell" owner:self options:nil] lastObject];
    }
    cell.backgroundColor = [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.loginTextFiel.delegate = self;
    cell.loginTextFiel.autocapitalizationType = UITextAutocapitalizationTypeNone;
    cell.loginTextFiel.autocorrectionType = UITextAutocorrectionTypeNo;
    cell.loginTextFiel.spellCheckingType = UITextSpellCheckingTypeNo;
    cell.loginTextFiel.clearButtonMode = UITextFieldViewModeAlways;
    cell.loginTextFiel.returnKeyType =UIReturnKeyDone;
    cell.loginTextFiel.font = [UIFont systemFontOfSize:16];
    cell.vLabel.text = [NSString stringWithFormat:@"V%@",apiVString];
    _loginText = cell.loginTextFiel;
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    NSString *textS = [userdf objectForKey:@"loginText"];
    if ([NSString isStringEmpty:textS] == NO) {
        _loginText.text = textS;
    }else {
        _loginText.text = @"";
    }
   
    
    cell.passwordTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    cell.passwordTextField.autocorrectionType = UITextAutocorrectionTypeNo;
    cell.passwordTextField.spellCheckingType = UITextSpellCheckingTypeNo;
    cell.passwordTextField.clearButtonMode = UITextFieldViewModeAlways;
    cell.passwordTextField.delegate = self;
    cell.passwordTextField.returnKeyType =UIReturnKeyDone;
    cell.passwordTextField.secureTextEntry = YES;
    cell.passwordTextField.font = [UIFont systemFontOfSize:16];
    _passordText = cell.passwordTextField;
    [cell.passwordTextField addTarget:self action:@selector(passwordTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

    cell.loginBtn.layer.masksToBounds = YES;
    cell.loginBtn.layer.cornerRadius = 5;
    [cell.loginBtn addTarget:self action:@selector(loginBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)passwordTextFieldDidChange:(UITextField *)textField {
    //LoginNewCell *cell = [_homeTableView  cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    if (textField == _passordText) {
        if (textField.text.length > 20) {
            textField.text = [textField.text substringToIndex:20];
        }
    }
}


- (void)loginBtnClick:(UIButton *)btn {
    NSLog(@"123131313");
    NSLog(@"l:%@",_loginText.text);
    NSLog(@"p:%@",_passordText.text);
    
    if (_loginText.text.length != 0) {
//        if(![_loginText.text isMobileNumberClassification] && ![_loginText.text isValidateEmail]) {
//            [self showToast:@"请输入正确的手机号"];
//            return;
//        } else{
//           
//            
//        }
        if (_passordText.text.length == 0) {
            [self showToast:@"请输入密码不能为空"];
            return;
        }
        if (_passordText.text.length < 6 ) {
            [self showToast:@"密码不能小于6位"];
            return;
        }
        NSLog(@"....... %ld",_passordText.text.length);
        if (_passordText.text.length > 20 ) {
            [self showToast:@"密码不能大于20位"];
            return;
        }
        
        [self showHud:@"正在登录请稍等..."];
        NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
        [userdf setObject:_loginText.text forKey:@"loginText"];
        [userdf synchronize];
        NSString *textS = [userdf objectForKey:@"loginText"];
        NSLog(@"%@",textS);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self postLoginApiLoginName:_loginText.text loginPwd:_passordText.text];
        });
    }else {
        [self showToast:@"账号不能为空！"];
        return;
    }

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{   // 点击return收起键盘（方法 1）
    [_loginText resignFirstResponder];  // 收键盘
    [_passordText resignFirstResponder];  // 收键盘
    return YES;
}

- (void)postLoginApiLoginName:(NSString *)loginName loginPwd:(NSString *)loginPwd {
    LoginApi *api = [[LoginApi alloc] initWith:loginName loginPwd:loginPwd];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        LoginApi *result = (LoginApi *)request;
        if (result.isSuccess) {
            Login *login = result.resultData;
            NSMutableArray *arr = [[NSMutableArray alloc] init];
            
            for (LoginHandImgList *list in login.loginHandImgList) {
                [arr addObject:list.handLogoImg];
            }
            NSString *logImageUrl;
            if (arr.count > 0) {
                if (EMM_WIDTH == 320) {
                    logImageUrl = [arr objectAtIndex:0];
                }else if (EMM_WIDTH == 375) {
                    logImageUrl = [arr objectAtIndex:1];
                }else if (EMM_WIDTH == 414) {
                    logImageUrl = [arr objectAtIndex:2];
                }
            }
            NSString *user = login.userId;
            NSString *tk = login.token;
            NSString *userName = login.userName;
            NSString *merchantId = login.merchantId;
            NSString *roleName = login.roleName;
            NSString *roleType = login.roleType;
            //新增字段
            NSString *isHomePage = login.isHomePage;
            NSString *isCustomer = login.isCustomer;
            NSString *isHouses = login.isHouses;
            NSString *isAnalysis = login.isAnalysis;
            NSString *isMine = login.isMine;
            NSString *isAddCustomer = login.isAddCustomer;
            NSString *isDistributionCustomer = login.isDistributionCustomer;
            NSString *isGradesMine = login.isGradesMine;
            NSString *isHeroListMine = login.isHeroListMine;
            NSString *isTeamRankingMine = login.isTeamRankingMine;
            NSString *isAddPaydeposit = login.isAddPaydeposit;
            NSString *isAddSigned = login.isAddSigned;
            NSString *isAddSubscribe = login.isAddSubscribe;
            
            //是否开通电话平台
            NSString *isPhoneInformation = login.isPhoneInformation;

            //是否已开通认筹功能：0、未开通；1、已开通
            NSString *isPaydeposit = login.isPaydeposit;
            
            NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
            [userdf setObject:user forKey:@"userNameId"];
            [userdf setObject:tk forKey:@"is_login"];
            [userdf setBool:YES forKey:@"isLoginSuc"];
            [userdf setObject:userName forKey:@"userName"];
            [userdf setObject:merchantId forKey:@"merchantId"];
            [userdf setObject:roleName forKey:@"roleName"];
            [userdf setObject:roleType forKey:@"roleType"];
          
            //新增字段
            [userdf setObject:isHomePage forKey:@"isHomePage"];
            [userdf setObject:isCustomer forKey:@"isCustomer"];
            [userdf setObject:isHouses forKey:@"isHouses"];
            [userdf setObject:isAnalysis forKey:@"isAnalysis"];
            [userdf setObject:isMine forKey:@"isMine"];
            [userdf setObject:isAddCustomer forKey:@"isAddCustomer"];
            [userdf setObject:isDistributionCustomer forKey:@"isDistributionCustomer"];
            [userdf setObject:isGradesMine forKey:@"isGradesMine"];
            [userdf setObject:isHeroListMine forKey:@"isHeroListMine"];
            [userdf setObject:isTeamRankingMine forKey:@"isTeamRankingMine"];
            [userdf setObject:logImageUrl forKey:@"handLogoImg"];
            [userdf setObject:isPhoneInformation forKey:@"isPhoneInformation"];
            [userdf setObject:isPaydeposit forKey:@"isPaydeposit"];
            [userdf setObject:isAddPaydeposit forKey:@"isAddPaydeposit"];
            [userdf setObject:isAddSigned forKey:@"isAddSigned"];
            [userdf setObject:isAddSubscribe forKey:@"isAddSubscribe"];

            [userdf synchronize];
            [self postGetProjectListApi];
            
        } else {
            [self showToast:result.resultData.errorMsg];
        }
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

//获取项目列表
- (void)postGetProjectListApi {
    
    GetProjectListApi *api = [[GetProjectListApi alloc] initWith];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetProjectListApi *result = (GetProjectListApi *)request;
        if (result.isSuccess) {
            GetProjectList *get = result.resultData;
            if (get.projectList.count > 0) {
                NSMutableArray *arr = [[NSMutableArray alloc] init];
                for (ProjectList *list in get.projectList) {
                    [arr addObject:list];
                }
                NSUserDefaults *userdfd = [NSUserDefaults standardUserDefaults];
                NSString *projectCode = [userdfd objectForKey:@"projectCode"];
                if ([NSString isStringEmpty2:projectCode] == NO) {
                    
                }else {
                    ProjectList *lsit1 = [arr objectAtIndex:0];
                    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
                    [userdf setObject:lsit1.projectCode forKey:@"projectCode"];
                    [userdf setObject:lsit1.projectId forKey:@"projectId"];
                    [userdf setObject:lsit1.projectName forKey:@"projectName"];
                    [userdf setObject:@"0" forKey:@"indexString"];
                    [userdf synchronize];
                }
                [appInstance showMain];
                
            }
        } else {
            // [self showToast:result.resultData.errorMsg];
            [appInstance showMain];
        }
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

@end
